from cqhttp import CQHttp
from bot_body import Bot_body
import logging
import colorful

class Bot_plugin():
    def __init__(self, bot_body:Bot_body, extra_master_qqs=[], name="echo context"):
        self.name = name
        self.bot_body = bot_body
        self.bot = bot_body.bot
        self.master_qqs = self.bot_body.master_qqs.union(extra_master_qqs)
        self.report_qq = self.bot_body.report_qq

    def register(self, post_type='message'):
        if post_type == 'message':
            registered_func = self.handle_msg
        elif post_type == 'request':
            registered_func = self.handle_request
        elif post_type == 'notice':
            registered_func = self.handle_notice
        else:
            raise Exception("arg 'post_type' should be in ['message', 'request', 'notice]")
        self.bot_body.register_on_type(
            func = registered_func,
            post_type = post_type,
            plugin_name = '{} - {}'.format(self.name, post_type)
        )

    def register_all(self):
        self.register('message')
        self.register('request')
        self.register('notice')


    def handle_msg(self, context):
        bot = self.bot
        logging.debug(colorful.cyan("Bot_plugin::handle_msg"))
        if context['user_id'] in self.master_qqs or \
            ('group_id' in context and context['group_id'] == 833736314):
            bot.send(context, "Message echo from {}: context={}".format(self.name, context), auto_escape=True)
            bot.send(context, message=context['message'])
    
    def handle_request(self, context):
        logging.debug(colorful.cyan("Bot_plugin::handle_request"))
        bot.send_private_msg(user_id=self.report_qq, message="Request echo from {}: context={}".format(self.name, context), auto_escape=True)

    def handle_notice(self, context):
        logging.debug(colorful.cyan("Bot_plugin::handle_notice"))
        self.bot.send_private_msg(user_id=self.report_qq, message="Notice echo from {}: context={}".format(self.name, context), auto_escape=True)

    


if __name__ == '__main__':
    bot_body = Bot_body()
    bot_plugin = Bot_plugin(bot_body)
    bot_plugin.register()
    bot_body.run()
